package com.xg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xg.common.constant.CommonStatusEnum;
import com.xg.common.request.OrderItemDTO;
import com.xg.common.request.UsedCarReq;
import com.xg.common.util.*;
import com.xg.common.result.ApiResult;
import com.xg.controller.dto.UsedCarDto;
import com.xg.remote.ServiceThirdFeignClient;
import com.xg.vo.UsedCarVO;
import com.xg.entity.UsedCar;
import com.xg.entity.UsedCarImage;
import com.xg.mapper.UsedCarImageMapper;
import com.xg.mapper.UsedCarMapper;
import com.xg.service.IUsedCarService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jdh
 * @since 2023-03-30
 */
@Service
public class UsedCarServiceImpl extends ServiceImpl<UsedCarMapper, UsedCar> implements IUsedCarService {

    @Autowired
    private UsedCarMapper usedCarMapper;

    @Autowired
    private UsedCarImageMapper imageMapper;

    @Autowired
    private ServiceThirdFeignClient thirdFeignClient;

    /**
     * @description: (汽车详情信息查询)
     * @author 荣晓凯
     * @date 2023/4/4 12:33
     * @version 1.0
     */
    @Override
    public UsedCarVO findCarList(Integer usedCarId) {
        UsedCarVO usedCarVO = usedCarMapper.findCarList(usedCarId);
        String images = usedCarVO.getImages();
        /*截取图片*/
        String[] split = images.split(",");
        usedCarVO.setImgs(split);
        return usedCarVO;
    }


    @Override
    public List<UsedCar> queryUsedCarList(Integer orderId,String usedCarName, Integer minPrice, Integer maxPrice) {
        UsedCar usedCar = new UsedCar();
        if (orderId != null ) {
            usedCar.setOrderId(orderId);
        }
        if (!StringUtils.isBlank(usedCarName)) {
            usedCar.setUsedCarName(usedCarName);
        }
        if (minPrice != null) {
            usedCar.setMinPrice(minPrice);
        }
        if (maxPrice != null) {
            usedCar.setMaxPrice(maxPrice);
        }
        return usedCarMapper.queryUsedCarList(usedCar);
    }

    @Override
    public List<UsedCar> queryUsedCarSearchList(UsedCar usedCar) {
        return usedCarMapper.queryUsedCarSearchList(usedCar);
    }

    /**
     * 车辆列表
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<UsedCar> queryWrapper = new QueryWrapper<>();
        IPage<UsedCar> pageUtil = new Page<UsedCar>(Long.parseLong((String) params.get("page")), Long.parseLong((String) params.get("limit")));
        IPage<List<UsedCar>> page = usedCarMapper.queryUsedCarSearchListCopy(pageUtil, params);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = RedisKeyUtils.QUERY_USEDCAR_REDIS_KEY,allEntries = true)
    public ApiResult saveUsedCar(UsedCar usedCar) {
        //如果传递usedCar的id为空表示新增
        if (Func.isEmpty(usedCar.getUsedCarId())) {
            //设置审核状态
            usedCar.setAuditStatus(2);
            usedCarMapper.insert(usedCar);
            //获取usedId进行图片的批量新增
            List<String> fileList = usedCar.getFileList();
            List<UsedCarImage> imgList = new ArrayList<>();
            fileList.forEach(e -> {
                UsedCarImage img = new UsedCarImage();
                img.setCarId(usedCar.getUsedCarId());
                img.setImagePath(e);
                imgList.add(img);
            });
            //批量新增车辆图片信息
            for (int i = 0; i < imgList.size(); i++) {
                imageMapper.insert(imgList.get(i));
            }
            return ApiResult.success().setCode(1).setMessage("新增成功");
        } else {
            usedCarMapper.updateById(usedCar);
            //获取usedId进行图片的批量新增
            List<UsedCarImage> imgList = new ArrayList<>();
            List<String> fileList = usedCar.getFileList();
            if (!Func.isEmpty(fileList)) {
                //先删再增
                Map<String, Object> map = new HashMap<>();
                map.put("car_id", usedCar.getUsedCarId());
                imageMapper.deleteByMap(map);
                fileList.forEach(e -> {
                    UsedCarImage img = new UsedCarImage();
                    img.setCarId(usedCar.getUsedCarId());
                    img.setImagePath(e);
                    imgList.add(img);
                });
                //批量新增车辆图片信息
                for (int i = 0; i < imgList.size(); i++) {
                    imageMapper.insert(imgList.get(i));
                }
            }
            return ApiResult.success().setCode(2).setMessage("更新成功");
        }
    }

    /**
     * 根据车辆id获取车辆详细信息
     *
     * @param carId
     * @return
     */
    @Override
    public OrderItemDTO getCarByCarId(Long carId) {
        return usedCarMapper.getCarByCarId(carId);
    }

    @Override
    public List<UsedCar> queryUsedCarListWithImages() {
        return usedCarMapper.queryUsedCarListWithImages();
    }

    @Override
    public PageUtil<UsedCar> findCarListNew(Map<String, Object> params) {
        List<UsedCar> list = usedCarMapper.queryUsedCarSearchListNewCopy(params);
        PageUtil<UsedCar> pageInfo = PageUtilHelper.pageHelper(list, Integer.parseInt((String) params.get("page")), Integer.parseInt((String) params.get("limit")));
        return pageInfo;
    }

    @Override
    public List<UsedCar> queryImagesWithStatus() {
        return usedCarMapper.queryImagesWithStatus();
    }

    @Override
    public List<UsedCar> queryImagesWithEnergy() {
        return usedCarMapper.queryImagesWithEnergy();
    }

    @Override
    public List<UsedCar> queryImagesWithType() {
        return usedCarMapper.queryImagesWithType();
    }

    @Override
    @Cacheable(cacheNames = RedisKeyUtils.QUERY_USEDCAR_REDIS_KEY,key = "#usedCarDto.usedCarName+#usedCarDto.brandId+#usedCarDto.seriesId+#usedCarDto.pricePre+#usedCarDto.priceEnd+#usedCarDto.carYearPre+#usedCarDto.carYearEnd+#usedCarDto.carGearbox+#usedCarDto.carType+#usedCarDto.carMileage+#usedCarDto.carDisplacementPre+#usedCarDto.carDisplacementEnd+#usedCarDto.carSeatNumber+#usedCarDto.carEnergy")
    public List<UsedCar> buySearchUsedCar(UsedCarDto usedCarDto) {
        LambdaQueryWrapper<UsedCar> queryWrapper = new LambdaQueryWrapper<>();
        //查询在售车辆
        queryWrapper.eq(UsedCar::getOnSale,1);
        //查询审核通过的车辆
        queryWrapper.eq(UsedCar::getAuditStatus,3);
        if (!Func.isEmpty(usedCarDto.getUsedCarName())){
            queryWrapper.like(UsedCar::getUsedCarName,usedCarDto.getUsedCarName());
        }
        if (!Func.isEmpty(usedCarDto.getBrandId())&&usedCarDto.getBrandId()!=0){
            queryWrapper.eq(UsedCar::getBrandId, usedCarDto.getBrandId());
        }
        if (!Func.isEmpty(usedCarDto.getSeriesId())&&usedCarDto.getSeriesId()!=0){
            queryWrapper.eq(UsedCar::getUsedCarSeriesId, usedCarDto.getSeriesId());
        }
        if (!Func.isEmpty(usedCarDto.getPricePre())){
            queryWrapper.ge(true,UsedCar::getUsedCarHandSale,usedCarDto.getPricePre());
        }
        if (!Func.isEmpty(usedCarDto.getPriceEnd())){
            queryWrapper.le(true,UsedCar::getUsedCarHandSale,usedCarDto.getPriceEnd());
        }
        if (!Func.isEmpty(usedCarDto.getCarYearPre())){
            queryWrapper.ge(true,UsedCar::getUsedCarRegistrationTime,usedCarDto.getCarYearPre());
        }
        if (!Func.isEmpty(usedCarDto.getCarYearEnd())){
            queryWrapper.le(true,UsedCar::getUsedCarRegistrationTime,usedCarDto.getCarYearEnd());
        }
        if (!Func.isEmpty(usedCarDto.getCarGearbox())&&usedCarDto.getCarGearbox()!=0){
            queryWrapper.eq(UsedCar::getUsedCarGearbox,usedCarDto.getCarGearbox());
        }
        if (!Func.isEmpty(usedCarDto.getCarType())&&usedCarDto.getCarType()!=0){
            queryWrapper.eq(UsedCar::getUsedCarTypeId,usedCarDto.getCarType());
        }
        if (!Func.isEmpty(usedCarDto.getCarMileage())&&usedCarDto.getCarMileage()!=0.0&&usedCarDto.getCarMileage()<6.0){
            queryWrapper.le(UsedCar::getUsedCarMileage,usedCarDto.getCarMileage());
        }
        if (!Func.isEmpty(usedCarDto.getCarMileage())&&usedCarDto.getCarMileage()>5.0) {
            queryWrapper.ge(UsedCar::getUsedCarMileage,5.0);
        }
        if (!Func.isEmpty(usedCarDto.getCarDisplacementPre())&&usedCarDto.getCarDisplacementPre()!=0.0){
            queryWrapper.ge(UsedCar::getUsedCarDisplacement,usedCarDto.getCarDisplacementPre());
        }
        if (!Func.isEmpty(usedCarDto.getCarDisplacementEnd())&&usedCarDto.getCarDisplacementEnd()!=0.0) {
            queryWrapper.le(UsedCar::getUsedCarDisplacement,usedCarDto.getCarDisplacementEnd());
        }
        if (!Func.isEmpty(usedCarDto.getCarSeatNumber())&&usedCarDto.getCarSeatNumber()!=0&&usedCarDto.getCarSeatNumber()<7){
            queryWrapper.eq(UsedCar::getUsedCarSeat,usedCarDto.getCarSeatNumber());
        }
        if (!Func.isEmpty(usedCarDto.getCarSeatNumber())&&usedCarDto.getCarSeatNumber()>7) {
            queryWrapper.ge(UsedCar::getUsedCarSeat,7);
        }
        if (!Func.isEmpty(usedCarDto.getCarEnergy())&&usedCarDto.getCarEnergy()!=0){
            queryWrapper.eq(UsedCar::getUsedCarEnergyPlanning,usedCarDto.getCarEnergy());
        }
        //先查询汽车主表
        List<UsedCar> carList = usedCarMapper.selectList(queryWrapper);
        //在查询图片表
        List<UsedCarImage> usedCarImages = imageMapper.selectList(null);
        //遍历图片主表将carId符合的对象放到汽车表集合中
        carList.forEach(c->{
            List<UsedCarImage> list = new ArrayList<>();
            usedCarImages.forEach(e->{
                if (c.getUsedCarId().equals(e.getCarId())){
                    list.add(e);
                }
            });
            c.setUsedCarImage(list);
        });
        return carList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = RedisKeyUtils.QUERY_USEDCAR_REDIS_KEY,allEntries = true)
    public void updateUsedCar(int parseInt) {
        usedCarMapper.updateUsedCar(parseInt);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = RedisKeyUtils.QUERY_USEDCAR_REDIS_KEY,allEntries = true)
    public ApiResult auditUsedCar(UsedCarReq usedCarReq) {
        int i = usedCarMapper.auditUsedCar(usedCarReq.getIds(),usedCarReq.getAuditStatus());
        if (i > 0) {
            return ApiResult.success();
        }
        return ApiResult.error(CommonStatusEnum.USED_CAR_AUDIT_ERROR.getCode(), CommonStatusEnum.USED_CAR_AUDIT_ERROR.getMsg());
    }

    @Override
    public List<UsedCar> queryCarList(Integer usedCarId) {
        return usedCarMapper.queryCarList(usedCarId);
    }

    /**
     * 删除
     *
     * @Author: JiaDeHao
     * @Date: 16:06 2023/4/4
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = RedisKeyUtils.QUERY_USEDCAR_REDIS_KEY,allEntries = true)
    public ApiResult deleteUsedCar(List<Integer> ids) {
        int i = usedCarMapper.deleteBatchIds(ids);
        if (i > 0) {
            return ApiResult.success();
        }
        return ApiResult.error(CommonStatusEnum.USED_CAR_DELETE_ERROR.getCode(), CommonStatusEnum.USED_CAR_DELETE_ERROR.getMsg());
    }

    @Override
    public ApiResult<UsedCar> selectUsedCarInfo(Integer usedCarId) {
        UsedCar usedCar = usedCarMapper.selectUsedCarInfo(usedCarId);
        if (!Func.isEmpty(usedCar)) {
            return ApiResult.success(usedCar);
        } else {
            return ApiResult.error(CommonStatusEnum.USED_CAR_INFO_ERROR.getCode(), CommonStatusEnum.USED_CAR_INFO_ERROR.getMsg());
        }
    }

    /**
     * @return
     * @return
     * @description: 卖车咨询发送短信
     * @author 荣晓凯
     * @date 2023/4/3 17:22
     * @version 1.0
     */
    @Override
    public String sendMsg(String phone) {
        thirdFeignClient.sendSellCode(phone);
        return phone;
    }


}
